package com.fengwk.support.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.fengwk.support.util.CodeUtils;
import com.fengwk.support.util.JsonUtils;
import com.fengwk.support.util.LoggerUtils;
import com.fengwk.support.util.LoggerUtils.Logger;

/**
 * 请求解析拦截器
 * 
 * @author fengwk
 * @version 创建时间:2017年7月21日 下午10:56:14
 */
public class RequestParseInterceptor implements HandlerInterceptor{  
	  
    private static final Logger LOG = LoggerUtils.getLogger(RequestParseInterceptor.class);
    
    private ThreadLocal<Long> timerThreadLocal = new ThreadLocal<Long>();
    private ThreadLocal<String> requestUrlThreadLocal = new ThreadLocal<String>();
    private ThreadLocal<String> parametersThreadLocal = new ThreadLocal<String>();
    private ThreadLocal<String> requestIdThreadLocal = new ThreadLocal<String>();
    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	String requestUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI();
       	String parameters = JsonUtils.toJson(request.getParameterMap());
    	String requestId = CodeUtils.uuid();
    	timerThreadLocal.set(System.currentTimeMillis());
    	requestUrlThreadLocal.set(requestUrl);
    	parametersThreadLocal.set(parameters);
    	requestIdThreadLocal.set(requestId);
    	LOG.info("request url ==> "+ requestUrl + "; param ==> "+ parameters + "; requestId ==> " + requestId);  
        return true;  
    }  
    
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    	// nothing to do
    }  
  
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {  
    	long executeTime = System.currentTimeMillis() - timerThreadLocal.get();
    	String requestUrl = requestUrlThreadLocal.get();
    	String parameters = parametersThreadLocal.get();
    	String requestId = requestIdThreadLocal.get();
    	timerThreadLocal.remove();
    	requestUrlThreadLocal.remove();
    	requestIdThreadLocal.remove();
    	LOG.info("request url ==> "+ requestUrl + "; executeTime ==> " + executeTime + "ms; param ==> "+ parameters + "; requestId ==> " + requestId);
    }  
}  